/* 日期tag选择组件 */
<template>
  <div class="container">
    <el-tag :style="{'cursor': inputDisabled ? 'not-allowed': 'pointer'}" type="success" effect="dark" @click="onAllItemClick">全选</el-tag>
    <el-tag
      :style="{'cursor': inputDisabled ? 'not-allowed': 'pointer'}"
      v-for="item in dataSource" 
      :key="item.value"
      :effect="getTagEffect(item.value)"
      @click="onNormalItemClick(item)"
    >{{ item.label }}</el-tag>
  </div>  
</template>

<script>
export default {
  inject: {
    elForm: {
      default: ''
    },
    elFormItem: {
      default: ''
    }
  },
  props: {
    value: {
      type: Array,
      default: _ => null
    },
    disabled: {
      type: Boolean,
      default: false
    },
    dataSource: {
      type: Array,
      default: _ => [
        { label: '周日', value: '7' },
        { label: '周一', value: '1' },
        { label: '周二', value: '2' },
        { label: '周三', value: '3' },
        { label: '周四', value: '4' },
        { label: '周五', value: '5' },
        { label: '周六', value: '6' },
      ]
    }
  },
  computed: {
    getTagEffect (val) {
      return val => this.value && this.value.includes(val) ? 'dark' : 'plain'
    },
    inputDisabled() {
      return this.disabled || (this.elForm || {}).disabled;
    }    
  },
  mounted () {
    // 处理默认值 - 当无值得时候，默认选中全部。
    // 当前使用情景：新增时候默认是选中所有，当详情及修改时显示的时回显数据
    // 该处理实际不应该放到组件内容，应该由外部传入prop来确定是否进行默认值覆盖
    if (this.value === null || this.value === undefined) {
      this.onAllItemClick()
    }
  },
  methods: {
    // 事件 - 普通tag触发
    onNormalItemClick (tagInfo) {
      if (this.inputDisabled) return

      const hasMatch = this.value && this.value.includes(tagInfo.value)
      hasMatch
        ? this.__emitEvent(this.value.filter(item => item !== tagInfo.value))
        : this.__emitEvent([...this.value, tagInfo.value])
    },
    // 事件 - 所有开关tag触发
    onAllItemClick () {
      if (this.inputDisabled) return
      
      const match = this.dataSource.map(item => item.value)
      JSON.stringify(match) === JSON.stringify(this.value)
        ? this.__emitEvent([])
        : this.__emitEvent(match)
    },
    // 方法 - 抛出事件
    __emitEvent (value) {
      this.$emit('input', value)
      this.$emit('change', value)
      this.$parent.$emit('el.form.change', value)
    }
  }
}
</script>

<style lang="scss" scoped>
  .container {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    .el-tag {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
</style>